package tpoo.server.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import tpoo.common.dto.model.users.UserDTO;
import tpoo.common.utils.passiveOperations.AfterLoginOperation;
import tpoo.server.model.users.User;

public class Server{

	private static Log logger= LogFactory.getLog(Server.class);
	
	private List<Client> registeredClients = Collections.synchronizedList(new ArrayList<Client>());
	
	public void registerClient(Client aClient){
		logger.info("Login de "+aClient);
		this.getRegisteredClients().add(aClient);		
	}
	
	private synchronized List<Client> getRegisteredClients() {
		return registeredClients;
	}

	public User getLoggedUser(String name){
		for (Client c : this.getRegisteredClients()){
			if (c.getUser().getUsername().equals(name))
				return c.getUser();
		}
		throw new RuntimeException("Usuario '"+name+"' parece no estar loggeado!");
	}

	public void logout(User loggedUser) {
		String name= loggedUser.getUsername();
		Client client2remove=null;
		for (Client client : this.getRegisteredClients()){
			if (client.getUser().getUsername().equals(name)){
				client2remove = client;
			}	
		}		
		// si se hace dentro del for, tira error de concurrencia
		// java.util.ConcurrentModificationException
		this.registeredClients.remove(client2remove);
		try {
			client2remove.finalize();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
